package esb.chapter4.messageflow.servicemix;

import javax.annotation.Resource;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import javax.xml.transform.Source;

import org.apache.log4j.Logger;
import org.apache.servicemix.MessageExchangeListener;
import org.apache.servicemix.components.util.ComponentSupport;
import org.apache.servicemix.jbi.jaxp.SourceTransformer;
import org.apache.servicemix.jbi.jaxp.StringSource;
import org.w3c.dom.Element;

import esb.chapter4.messageflow.domain.BookQuote;
import esb.chapter4.messageflow.service.util.QuoteMessageHelper;

public class AggregateMessageLogger extends ComponentSupport implements MessageExchangeListener {

	private final static Logger logger = Logger.getLogger(AggregateMessageLogger.class);
	private SourceTransformer sourceTransformer = new SourceTransformer();
	@Resource
	private DeliveryChannel channel;

    public void onMessageExchange(MessageExchange exchange) throws MessagingException {
    	if (exchange.getStatus() != ExchangeStatus.ACTIVE) {
    		logger.info("state is not active so ignoring call");
    		return;
    	}
    	Element payloadElem = null;
    	try {
    		Source contentSource = getInMessage(exchange).getContent();
    		payloadElem = sourceTransformer.toDOMElement(contentSource);
        } catch(Exception e) {
        	logger.error("error while reading payload", e);
        }
        BookQuote bookQuote = QuoteMessageHelper.unmarshallQuote(payloadElem);
        logger.info("received quote " + bookQuote.getIsbn() + ", " 
        		+ bookQuote.getPrice() + ", " + bookQuote.getCompanyName());
    	NormalizedMessage outMessage = exchange.createMessage();
    	try {
    		outMessage.setContent(new StringSource(QuoteMessageHelper.marshallQuote(bookQuote)));
    	} catch(Exception e) {
    		logger.error("error while setting content in out message", e);
    	}
        outMessage.setProperty("org.apache.servicemix.eip.splitter.corrid", bookQuote.getIsbn());
        Integer aggregatorIndex = null;
        if("Amazon".equalsIgnoreCase(bookQuote.getCompanyName())) {
        	aggregatorIndex = new Integer(0);
        } else if("BarnesAndNoble".equalsIgnoreCase(bookQuote.getCompanyName())) {
        	aggregatorIndex = new Integer(1);
        }
        outMessage.setProperty("org.apache.servicemix.eip.splitter.index", aggregatorIndex);
        outMessage.setProperty("org.apache.servicemix.eip.splitter.count", new Integer(2));
        exchange.setMessage(outMessage, "out");
        channel.send(exchange);
    }
}
